package com.qianjiangcloud.store.activity;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.qianjiangcloud.store.BaseDoFragment;
import com.qianjiangcloud.store.Run;
import com.qianjiangcloud.store.http.JsonRequestBean;
import com.qianjiangcloud.store.http.JsonTask;
import com.qianjiangcloud.store.http.JsonTaskHandler;
import com.qianjiangcloud.store.ui.CommonTextView;
import com.qianjiangcloud.store.ui.NoScrollListView;
import com.qianjiangcloud.store.ui.XPullDownListView;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import com.qianjiangcloud.store.R;
import com.qianjiangcloud.store.libary.cache.MyImageLoader;


/**
 * Created by Jelly on 2016/8/1.
 */
public class AccountSalesOrderFragment extends BaseDoFragment implements
        XPullDownListView.IXListViewListener {

    private XPullDownListView mListView;
    private OrderStatueAdapter mAdatpter;
    private RelativeLayout mEmptyViewRL;
    private int mPageNum = 1;
    private int mTotalResult = 5;
    private boolean isLoadedAll;// 是否已经拿完服务器所有数据
    private DecimalFormat mDecimalFormat = new DecimalFormat("0.00");

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mActionBar.setTitle(mActivity.getString(R.string.select_after_sales_order));
        rootView = inflater.inflate(R.layout.fragment_after_sales_order, null);
        mListView = (XPullDownListView) findViewById(R.id.customer_order_listview);
        mEmptyViewRL = (RelativeLayout) findViewById(R.id.search_error_rl);
        mEmptyViewRL.setVisibility(View.GONE);
        mListView.setEmptyView(mEmptyViewRL);
        mAdatpter = new OrderStatueAdapter();
        mListView.setAdapter(mAdatpter);
        mListView.setXPullDownListViewListener(this);
        mListView.setPullLoadEnable(false);
        firstLoad();
    }

    private class OrderStatueAdapter extends BaseAdapter implements View.OnClickListener {

        private ViewHolder mHolder;

        @Override
        public int getCount() {
            return mResultLists.size();
        }

        @Override
        public Object getItem(int position) {
            return mResultLists.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                mHolder = new ViewHolder();
                convertView = View.inflate(mActivity, R.layout.item_myorder_statue, null);
                mHolder.mConsigneeTV = (TextView) convertView.findViewById(R.id.order_tv_consignee);
                mHolder.freightTV= (CommonTextView) convertView.findViewById(R.id.order_tv_paid_price);
                mHolder.numberTV= (CommonTextView) convertView.findViewById(R.id.account_orders_item_goods_num);
                mHolder.mStatueTV = (TextView) convertView.findViewById(R.id.order_tv_statue);
                mHolder.mPaidPriceTV = (CommonTextView) convertView.findViewById(R.id.account_orders_item_price);
                //取消
                mHolder.mCancelBT = (Button) convertView.findViewById(R.id.order_bt_cancel);
                //去支付
                mHolder.mPayBT = (Button) convertView.findViewById(R.id.order_bt_pay);
                mHolder.mListView = (NoScrollListView) convertView.findViewById(R.id.myListView1);
                //去付款
                mHolder.mAffirm = (Button) convertView.findViewById(R.id.order_bt_affirm);
                //查看物流
                mHolder.mLogistics = (Button) convertView.findViewById(R.id.order_bt_logistics);
                mHolder.table= (TableRow) convertView.findViewById(R.id.table);
                convertView.setTag(mHolder);
            } else {
                mHolder = (ViewHolder) convertView.getTag();
            }
            mHolder.mStatueTV.setVisibility(View.GONE);

            JSONObject mJsonObject = mResultLists.get(position);
            JSONObject order = mJsonObject;

            mHolder.mCancelBT.setVisibility(View.GONE);
            mHolder.mPayBT.setVisibility(View.GONE);
            mHolder.mAffirm.setVisibility(View.GONE);
            mHolder.mLogistics.setVisibility(View.GONE);
            mHolder.mLogistics.setTag(position);
            mHolder.table.setTag(position);
            mHolder.mLogistics.setOnClickListener(this);
            mHolder.mLogistics.setVisibility(View.VISIBLE);
            mHolder.mLogistics.setText("申请退货");
            mHolder.mLogistics.setOnClickListener(this);
            mHolder.table.setOnClickListener(this);



            // 收货人 改为订单编号
            mHolder.freightTV.setText(mJsonObject.optJSONObject("shipping").optString("cost_shipping")+"元");
            mHolder.numberTV.setText(" "+mJsonObject.optString("itemnum")+" ");
            mHolder.mConsigneeTV.setText("订单号: "+mJsonObject.optString("order_id"));
            // 实付金额
            double mPaidPrice = order.optDouble("total_amount");
            mHolder.mPaidPriceTV.setText(getString(R.string.confirm_order_fee, mDecimalFormat.format(mPaidPrice)));
            // 所有商品
            mHolder.mListView.setAdapter(new OrderStatueChildAdapter(order.optJSONArray("goods_items")));
           /* convertView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    startActivity(AgentActivity
                            .intentForFragment(mActivity, AgentActivity.FRAGMENT_GOODS_ORDERS_DETAIL).putExtra(
                                    "orderId", mResultLists.get(position).optString("order_id")));
                }
            });*/
            return convertView;
        }

        private class ViewHolder {
            public TextView mConsigneeTV, mStatueTV;
            public CommonTextView mPaidPriceTV,freightTV,numberTV;
            public NoScrollListView mListView;
            public Button mCancelBT, mPayBT, mAffirm, mLogistics;
            public TableRow table;
        }

        @Override
        public void onClick(View v) {
            Integer postion= (Integer) v.getTag();
            if (v.getId()==R.id.table){
                startActivity(AgentActivity
                        .intentForFragment(mActivity, AgentActivity.FRAGMENT_GOODS_ORDERS_DETAIL).putExtra(
                                "orderId", mResultLists.get(postion).optString("order_id")));
            }
            if (v.getId()==R.id.order_bt_logistics){
                startActivity(AgentActivity.intentForFragment(mActivity,AgentActivity.FRAGMENT_AFTER_SELECT_GOOD)
                        .putExtra("orderId",mResultLists.get(postion).optString("order_id")));

            }

        }
    }

    private class OrderStatueChildAdapter extends BaseAdapter implements View.OnClickListener {
        private ViewHolder mHolder;
        public List<JSONObject> mShoppLists = new ArrayList<JSONObject>();

        public OrderStatueChildAdapter(JSONArray json) {
            try {
                if (json != null && json.length() > 0) {
                    this.mShoppLists.clear();
                    for (int i = 0; i < json.length(); i++) {
                        this.mShoppLists.add(json.getJSONObject(i));
                    }
                }
            } catch (Exception e) {
            }
        }

        @Override
        public int getCount() {
            return mShoppLists.size();
        }

        @Override
        public Object getItem(int position) {
            return mShoppLists.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                mHolder = new ViewHolder();
                convertView = View.inflate(mActivity, R.layout.item_order_statue_child, null);
                mHolder.mShoppIconIV = (ImageView) convertView.findViewById(R.id.order_iv_shopp_icon);
                mHolder.mShoppNameTV = (TextView) convertView.findViewById(R.id.order_tv_shopp_name);
                mHolder.mShoppTotalPrice = (TextView) convertView.findViewById(R.id.order_tv_shopp_total_price);
                mHolder.mShoppNumberTV = (TextView) convertView.findViewById(R.id.order_tv_shopp_number);
                mHolder.mLayout = (LinearLayout) convertView.findViewById(R.id.order_statue_ll);
                mHolder.shopInfo= (TextView) convertView.findViewById(R.id.order_tv_shopp_info);
                mHolder.mLayout.setOnClickListener(this);
                convertView.setTag(mHolder);
            } else {
                mHolder = (ViewHolder) convertView.getTag();
            }

            JSONObject mJsonObject = mShoppLists.get(position);
            JSONObject product = mJsonObject.optJSONObject("product");
            mHolder.mLayout.setTag(product);

            if (position >= mShoppLists.size() - 1) {
                ((View) convertView.findViewById(R.id.order_view)).setVisibility(View.GONE);
            } else {
                ((View) convertView.findViewById(R.id.order_view)).setVisibility(View.VISIBLE);
            }

            MyImageLoader.displayDefaultImage(product.optString("thumbnail_pic_src"),mHolder.mShoppIconIV);
            mHolder.mShoppNameTV.setText(product.optString("name"));
            mHolder.mShoppTotalPrice.setText(mActivity.getString(R.string.shopping_car_price,
                    mDecimalFormat.format(product.optDouble("price") * product.optInt("quantity"))));
            mHolder.mShoppNumberTV.setText("x " + product.optString("quantity"));
            try {
                if(null!=product.optString("products")) {
                    JSONObject object = new JSONObject(product.optString("products"));
                    if(!object.optString("spec_info").equals("null")) {
                        mHolder.shopInfo.setText(object.optString("spec_info"));
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return convertView;
        }

        private class ViewHolder {
            public LinearLayout mLayout;
            public ImageView mShoppIconIV;
            public TextView mShoppNameTV, mShoppTotalPrice, mShoppNumberTV,shopInfo;
        }

        @Override
        public void onClick(View v) {
            JSONObject product = (JSONObject) v.getTag();
            startActivity(AgentActivity.intentForFragment(mActivity, AgentActivity.FRAGMENT_GOODS_DETAIL)
                    .putExtra(Run.EXTRA_CLASS_ID, product.optString("goods_id")));
        }
    }

    private boolean isShowProgressDialog;
    private List<JSONObject> mResultLists = new ArrayList<JSONObject>();

    private class ObtainOrderListsTask implements JsonTaskHandler {

        {
            if (mPageNum == 1) {
                mResultLists.clear();
                // mAdatpter.notifyDataSetChanged();
                mListView.setPullLoadEnable(false);
            }
        }

        @Override
        public void task_response(String json_str) {
            JSONArray data = null;
            try {
                JSONObject mJsonObject = new JSONObject(json_str);
                JSONObject object=mJsonObject.optJSONObject("data");
                data=object.optJSONArray("data");
                if (Run.checkRequestJson(mActivity, mJsonObject)) {
                    if (data != null && data.length() > 0) {
                        for (int i = 0; i < data.length(); i++) {
                            mResultLists.add(data.optJSONObject(i));
                        }
                    }

                    if (data == null || data.length() < mTotalResult) {
                        isLoadedAll = true;
                    }
                }
            } catch (Exception e) {
            } finally {
                onStopLoad();
                hideLoadingDialog();
                mAdatpter.notifyDataSetChanged();

                if (data != null && data.length() >= mTotalResult) {
                    mListView.setPullLoadEnable(true);
                } else {
                    mListView.setPullLoadEnable(false);
                }

                if (mResultLists.size() > 0) {
                    mEmptyViewRL.setVisibility(View.GONE);
                } else {
                    mEmptyViewRL.setVisibility(View.VISIBLE);
                }
            }
        }

        @Override
        public JsonRequestBean task_request() {
            if (isShowProgressDialog) {
                showCancelableLoadingDialog();
            }
            JsonRequestBean mBean = new JsonRequestBean( "mobileapi.aftersales.afterlist");
            mBean.addParams("n_page", String.valueOf(mPageNum));
            return mBean;
        }
    }



    @Override
    public void onResume() {
        super.onResume();
        mEmptyViewRL.setVisibility(View.GONE);
    }



    private void firstLoad() {
        isShowProgressDialog = true;
        mPageNum = 1;
        loadNextPage(mPageNum);
    }

    private void loadNextPage(int pageNumber) {
        if (pageNumber == 1) {
            isLoadedAll = false;
        }

        if (isLoadedAll) {
            return;
        }
        Run.excuteJsonTask(new JsonTask(), new ObtainOrderListsTask());
    }

    @Override
    public void onRefresh() {
        isShowProgressDialog = false;
        mPageNum = 1;
        loadNextPage(mPageNum);
    }

    @Override
    public void onLoadMore() {
        isShowProgressDialog = false;
        mPageNum++;
        loadNextPage(mPageNum);
    }

    // 停止刷新
    private void onStopLoad() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime("刚刚");
    }

}
